package com.dries.portal.module.chat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dries.common.api.CommonResult;
import com.dries.portal.module.chat.constants.ChatConstant;
import com.dries.portal.module.chat.entity.GroupChat;
import com.dries.portal.module.chat.service.IGroupChatService;
import com.dries.security.service.RedisService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群组
 *
 * @author dries
 * @email samphsanie@gmail.com
 * @date 2020-08-30 17:09:25
 */
@RestController
@RequestMapping("chat/group")
public class GroupChatController {

    @Resource
    private IGroupChatService groupChatService;
    @Resource
    private RedisService redisService;

    /**
     * 列表
     */
    @ApiOperation("房间列表")
    @GetMapping("/list")
    public CommonResult list(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                             @RequestParam(required = false, defaultValue = "10") Integer pageSize){

        PageHelper.startPage(pageNum, pageSize);
        List<GroupChat> list = groupChatService.list(new QueryWrapper<GroupChat>()
                .lambda()
                .orderByDesc(GroupChat::getCreateTime)
        );
        PageInfo<GroupChat> pageInfo = new PageInfo<>(list);
        return CommonResult.success(pageInfo);
    }


    /**
     * 信息
     */
    @ApiOperation("房间信息")
    @GetMapping("/info/{id}")
    public CommonResult info(@PathVariable("id") Integer id){
		GroupChat groupChat = groupChatService.getById(id);

        return CommonResult.success(groupChat);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public CommonResult save(@RequestBody GroupChat groupChat){
		groupChatService.save(groupChat);

        return CommonResult.success();
    }

    /**
     * 修改
     */
    @ApiOperation("修改房间信息")
    @PutMapping("/update")
    public CommonResult update(@RequestBody GroupChat groupChat){
		groupChatService.updateById(groupChat);

        return CommonResult.success();
    }

    /**
     * 删除
     */
    @ApiOperation("删除房间")
    @DeleteMapping("/delete")
    public CommonResult delete(@RequestBody Integer[] ids){
		groupChatService.removeByIds(Arrays.asList(ids));
        List<String> collect = Arrays.stream(ids).map(e -> ChatConstant.CHAT_GROUP_ONLINE_KEY + e).collect(Collectors.toList());
        redisService.del(collect);
        return CommonResult.success();
    }

}
